//! # 依赖注入容器核心实现
//! 
//! 本模块实现了依赖注入容器的核心功能，包括组件注册、解析、生命周期管理等。

use crate::di::traits::*;
use crate::di::models::*;
use rustcloud_core::{ServiceResult, ServiceError};
use std::any::{Any, TypeId};
use std::collections::HashMap;
use std::sync::Arc;
use tokio::sync::RwLock;
use async_trait::async_trait;
use tracing;

/// 依赖注入容器实现
#[derive(Debug)]
pub struct DIContainer {
    registrations: Arc<RwLock<HashMap<TypeId, ComponentRegistration>>>,
    singletons: Arc<RwLock<HashMap<TypeId, ComponentInstance>>>,
    scoped_instances: Arc<RwLock<HashMap<String, HashMap<TypeId, ComponentInstance>>>>,
    state: Arc<RwLock<ComponentState>>,
}

impl Default for DIContainer {
    fn default() -> Self { Self::new() }
}

impl DIContainer {
    /// 创建新的依赖注入容器
    pub fn new() -> Self {
        Self {
            registrations: Arc::new(RwLock::new(HashMap::new())),
            singletons: Arc::new(RwLock::new(HashMap::new())),
            scoped_instances: Arc::new(RwLock::new(HashMap::new())),
            state: Arc::new(RwLock::new(ComponentState::Uninitialized)),
        }
    }

    /// 注册单例组件
    pub async fn register_singleton<T: 'static>(
        &self,
        name: &str,
        factory: impl ComponentFactory<T> + 'static,
    ) -> ServiceResult<()> {
        let metadata = ComponentMetadata::new(name)
            .with_lifecycle(ComponentLifecycle::Singleton);
        self.register(metadata, factory).await
    }

    /// 注册瞬态组件
    pub async fn register_transient<T: 'static>(
        &self,
        name: &str,
        factory: impl ComponentFactory<T> + 'static,
    ) -> ServiceResult<()> {
        let metadata = ComponentMetadata::new(name)
            .with_lifecycle(ComponentLifecycle::Transient);
        self.register(metadata, factory).await
    }

    /// 在指定作用域中解析组件
    pub async fn resolve_with_scope<T: 'static>(
        &self,
        scope: Option<&str>,
    ) -> ServiceResult<Arc<T>> {
        let type_id = TypeId::of::<T>();
        
        let registration = {
            let registrations = self.registrations.read().await;
            registrations.get(&type_id).cloned()
                .ok_or_else(|| ServiceError::InternalError(format!("组件未注册: {:?}", type_id)))?
        };

        match registration.metadata.lifecycle {
            ComponentLifecycle::Singleton => self.resolve_singleton::<T>(&registration).await,
            ComponentLifecycle::Transient => self.resolve_transient::<T>(&registration).await,
            ComponentLifecycle::Scoped => self.resolve_scoped::<T>(&registration, scope).await,
            ComponentLifecycle::ThreadLocal => self.resolve_transient::<T>(&registration).await,
        }
    }

    /// 获取容器状态
    pub async fn get_state(&self) -> ComponentState {
        self.state.read().await.clone()
    }

    /// 清理指定作用域
    pub async fn clear_scope(&self, scope: &str) -> ServiceResult<()> {
        let mut scoped_instances = self.scoped_instances.write().await;
        if let Some(scope_cache) = scoped_instances.remove(scope) {
            drop(scoped_instances);
            
            for (_, instance) in scope_cache {
                self.stop_component_instance(&instance).await?;
            }
            
            tracing::info!("作用域清理完成: {}", scope);
        }
        Ok(())
    }

    // 私有辅助方法
    async fn resolve_singleton<T: 'static>(
        &self,
        registration: &ComponentRegistration,
    ) -> ServiceResult<Arc<T>> {
        let type_id = TypeId::of::<T>();
        
        // 双重检查锁定
        {
            let singletons = self.singletons.read().await;
            if let Some(instance) = singletons.get(&type_id) {
                return self.cast_instance::<T>(instance);
            }
        }

        let mut singletons = self.singletons.write().await;
        if let Some(instance) = singletons.get(&type_id) {
            return self.cast_instance::<T>(instance);
        }

        let instance = self.create_component_instance::<T>(registration).await?;
        
        let component_instance = ComponentInstance {
            type_id,
            instance: instance.clone(),
            metadata: registration.metadata.clone(),
            state: Arc::new(RwLock::new(ComponentState::Running)),
            created_at: std::time::Instant::now(),
            last_accessed: Arc::new(RwLock::new(std::time::Instant::now())),
        };
        
        singletons.insert(type_id, component_instance);
        Ok(instance)
    }

    async fn resolve_transient<T: 'static>(
        &self,
        registration: &ComponentRegistration,
    ) -> ServiceResult<Arc<T>> {
        self.create_component_instance::<T>(registration).await
    }

    async fn resolve_scoped<T: 'static>(
        &self,
        registration: &ComponentRegistration,
        scope: Option<&str>,
    ) -> ServiceResult<Arc<T>> {
        let type_id = TypeId::of::<T>();
        let scope_key = scope.unwrap_or("default");

        {
            let scoped_instances = self.scoped_instances.read().await;
            if let Some(scope_cache) = scoped_instances.get(scope_key) {
                if let Some(instance) = scope_cache.get(&type_id) {
                    return self.cast_instance::<T>(instance);
                }
            }
        }

        let instance = self.create_component_instance::<T>(registration).await?;
        
        let component_instance = ComponentInstance {
            type_id,
            instance: instance.clone(),
            metadata: registration.metadata.clone(),
            state: Arc::new(RwLock::new(ComponentState::Running)),
            created_at: std::time::Instant::now(),
            last_accessed: Arc::new(RwLock::new(std::time::Instant::now())),
        };

        {
            let mut scoped_instances = self.scoped_instances.write().await;
            let scope_cache = scoped_instances
                .entry(scope_key.to_string())
                .or_insert_with(HashMap::new);
            scope_cache.insert(type_id, component_instance);
        }

        Ok(instance)
    }

    async fn create_component_instance<T: 'static>(
        &self,
        registration: &ComponentRegistration,
    ) -> ServiceResult<Arc<T>> {
        let factory = registration.factory
            .downcast_ref::<Box<dyn ComponentFactory<T>>>()
            .ok_or_else(|| ServiceError::InternalError("组件工厂类型转换失败".to_string()))?;

        factory.create(self).await
    }

    fn cast_instance<T: 'static>(&self, instance: &ComponentInstance) -> ServiceResult<Arc<T>> {
        instance.instance
            .clone()
            .downcast::<T>()
            .map_err(|_| ServiceError::InternalError("组件类型转换失败".to_string()))
    }

    async fn stop_component_instance(&self, instance: &ComponentInstance) -> ServiceResult<()> {
        if let Ok(lifecycle_manager) = instance.instance
            .clone()
            .downcast::<dyn ComponentLifecycleManager>() 
        {
            lifecycle_manager.stop().await?;
            lifecycle_manager.destroy().await?;
        }
        Ok(())
    }
}

#[async_trait]
impl Container for DIContainer {
    async fn register<T: 'static>(
        &self,
        metadata: ComponentMetadata,
        factory: impl ComponentFactory<T> + 'static,
    ) -> ServiceResult<()> {
        let type_id = TypeId::of::<T>();
        
        if self.is_registered::<T>().await {
            return Err(ServiceError::InternalError(format!(
                "组件已经注册: {}",
                metadata.name
            )));
        }

        let dependencies = factory.dependencies();
        let registration = ComponentRegistration {
            type_id,
            metadata: metadata.clone(),
            factory: Box::new(Box::new(factory) as Box<dyn Any + Send + Sync>),
            dependencies,
            state: Arc::new(RwLock::new(ComponentState::Uninitialized)),
        };

        let mut registrations = self.registrations.write().await;
        registrations.insert(type_id, registration);

        tracing::info!("组件注册成功: {} ({})", metadata.name, std::any::type_name::<T>());
        Ok(())
    }

    async fn resolve<T: 'static>(&self) -> ServiceResult<Arc<T>> {
        self.resolve_with_scope::<T>(None).await
    }

    async fn is_registered<T: 'static>(&self) -> bool {
        let type_id = TypeId::of::<T>();
        let registrations = self.registrations.read().await;
        registrations.contains_key(&type_id)
    }

    async fn start(&self) -> ServiceResult<()> {
        {
            let mut state = self.state.write().await;
            *state = ComponentState::Starting;
        }

        // 启动所有单例组件
        let singleton_types: Vec<TypeId> = {
            let registrations = self.registrations.read().await;
            registrations
                .values()
                .filter(|reg| reg.metadata.lifecycle == ComponentLifecycle::Singleton)
                .map(|reg| reg.type_id)
                .collect()
        };

        for type_id in singleton_types {
            // 触发单例创建
            tracing::debug!("启动单例组件: {:?}", type_id);
        }

        {
            let mut state = self.state.write().await;
            *state = ComponentState::Running;
        }

        tracing::info!("依赖注入容器启动完成");
        Ok(())
    }

    async fn stop(&self) -> ServiceResult<()> {
        {
            let mut state = self.state.write().await;
            *state = ComponentState::Stopping;
        }

        // 停止所有单例组件
        let singletons = {
            let singletons = self.singletons.read().await;
            singletons.values().cloned().collect::<Vec<_>>()
        };

        for instance in singletons {
            self.stop_component_instance(&instance).await?;
        }

        // 清理所有作用域
        let scope_keys: Vec<String> = {
            let scoped_instances = self.scoped_instances.read().await;
            scoped_instances.keys().cloned().collect()
        };

        for scope_key in scope_keys {
            self.clear_scope(&scope_key).await?;
        }

        {
            let mut state = self.state.write().await;
            *state = ComponentState::Stopped;
        }

        tracing::info!("依赖注入容器停止完成");
        Ok(())
    }
}